class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        ArrayList<Integer> temp = new ArrayList();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int n = 1, m = 1;   //m用于记录奇数偶数
        while(!queue.isEmpty()) {
            TreeNode current = queue.poll();
            n--;
            temp.add(current.val);

            if(current.left != null) {
                queue.offer(current.left);
            }

            if(current.right != null) {
                queue.offer(current.right);
            }

            if(n == 0) {
                n = queue.size();
                if(m % 2 == 0) {
                    Collections.reverse(temp);  //注意：这个接口要背
                }
                ans.add(temp);
                temp = new ArrayList();
                m++;
            }
        }

        return ans;
    }
}